<template lang="pug">
ECharts.pressure-flux-chart(
  ref="echarts"
  :options="options"
  auto-resize
  @click="selectItem")
</template>

<script>
/**
 * @name PressureFluxChart 压力流量图
 * @author caixq&wangrf
 * @description 展示瞬时压力与流量
 */
import { groupBy, values } from 'lodash'
export default {
  name: 'PressureFluxChart',
  props: {
    target: String,
    parameterList: Array,
    devicesData: Array
  },
  data () {
    return {
      options: {},
      targetList: [{
        name: 'flux',
        label: '瞬时流量',
        unit: 'm³/h'
      }, {
        name: 'pressure',
        label: '压力',
        unit: 'MPa'
      }]
    }
  },
  computed: {
    isMulti () {
      return this.devicesData.length > 1
    },
    series () {
      const data = this.devicesData.reduce((result, device) => {
        return [...result, ...this.targetList.map((item, index) => {
          return {
            type: 'line',
            xAxisIndex: index,
            yAxisIndex: index,
            symbolSize: 8,
            showSymbol: false,
            hoverAnimation: false,
            name: this.isMulti ? (device.siteName || '-') + '(' + device.siteCode + ')' : item.label,
            data: device.data.map((record) => this.formatValue(record[item.name])),
            markPoint: {
              symbol: 'pin',
              symbolSize: (value, params) => {
                let width = this.formatValue(value).length * 14
                width = (width < 40) ? 40 : width
                return [width, 40]
              },
              label: {
                formatter: ({seriesName, name, value}) => {
                  return `${this.formatValue(value) || '-'}`
                }
              },
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            }
            // markPoint: {
            //   symbolSize: 1,
            //   symbolOffset: [0, '50%'],
            //   label: {
            //     offset: [0, -15],
            //     formatter: ({seriesName, name, value}) => {
            //       return `${seriesName}${name}：${this.formatValue(value) || '-'} ${item.unit}`
            //     },
            //     backgroundColor: 'rgba(0,0,0,0.7)',
            //     borderRadius: 15,
            //     padding: [4, 10],
            //     lineHeight: 15,
            //     height: 15,
            //     distance: 20,
            //     color: '#fff',
            //     textBorderColor: '#000',
            //     fontSize: 12,
            //     fontWeight: 'bold',
            //     fontFamily: 'Microsoft YaHei',
            //     textBorderWidth: 1
            //   },
            //   data: this.isMulti ? [] : [
            //     {type: 'max', name: '最大值'},
            //     {type: 'min', name: '最小值'}
            //   ]
            // }
          }
        })]
      }, [])
      return data
    },
    legend () {
      const data = this.isMulti ? this.devicesData.reduce((result, device) => {
        return [...result, (device.siteName || '-') + '(' + device.siteCode + ')']
      }, []) : this.targetList.map(({label}) => label)
      return data
    },
    tipPosition () {
      return this.isMulti ? {
        position: function (pos, params, el, elRect, size) {
          var obj = {top: 10}
          obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30
          return obj
        }
      } : {}
    }
  },
  watch: {
    devicesData (data) {
      const xAxis = data[0].data.map(({recordTime}) => this.$moment(recordTime, 'x').format('YYYY-MM-DD HH:mm'))
      this.options = {
        color: ['#0000EE', '#CD0000', '#fec450', '#fc5929', '#83c9c7', '#2e4672', '#a1bb1c', '#fdad5b'],
        tooltip: {
          ...this.tipPosition,
          trigger: 'axis',
          axisPointer: {
            animation: false,
            label: {
              show: false
            },
            type: 'cross'
          },
          textStyle: {
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Microsoft YaHei'
          },
          formatter: this.isMulti ? (param) => {
            const siteList = values(groupBy(param, 'seriesName'))
            const text = siteList.reduce((result, site) => {
              return result + site.reduce((row, { axisIndex, value }) => {
                const label = this.targetList[axisIndex].label
                const unit = this.targetList[axisIndex].unit
                const content = (this.formatValue(value) || '-') + ' ' + unit
                return `${row}<div style="margin-left: 14px;">${label === '压力' ? '压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力' : label}：${content}</div>`
              }, `<div>${site[0].marker}${site[0].seriesName}：`)
            }, siteList[0][0].axisValue)
            return text
          } : (param) => {
            const text = param.reduce((result, site) => {
              return result + `<div>${site.marker}${site.seriesName === '压力' ? '压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力' : site.seriesName}：${this.formatValue(site.value) || '-'} ${this.targetList.find(item => item.label === site.seriesName).unit}</div>`
            }, param[0].axisValue)
            return text
          }
        },
        legend: {
          type: 'scroll',
          width: '92%',
          data: this.legend,
          y: '94%'
        },
        axisPointer: {
          link: {xAxisIndex: 'all'}
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1],
            y: '85%'
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1]
          }
        ],
        grid: [{
          left: 50,
          right: 15,
          top: '8%',
          height: '30%'
        }, {
          left: 50,
          right: 12,
          top: '48%',
          height: '30%'
        }],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLine: {onZero: true},
            data: xAxis,
            show: false
          },
          {
            gridIndex: 1,
            type: 'category',
            boundaryGap: false,
            axisLine: {onZero: true},
            data: xAxis,
            position: 'bottom'
          }
        ],
        yAxis: this.targetList.map(({label, unit}, gridIndex) => {
          return {
            gridIndex,
            name: `${label}(${unit})`,
            type: 'value',
            scale: true
          }
        }),
        series: this.series
      }
    }
  },
  methods: {
    formatValue (value) {
      return (value != null && value !== undefined) ? parseFloat(value).toFixed(3) : null
    },
    selectItem (data) {
      this.$emit('highLightTable', data)
    }
  }
}
</script>

<style lang="sass" scoped>
.pressure-flux-chart
  width: 100%
  height: 100%
</style>
